package com.faintlight.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private static final String[] WARM_TIPS = {
        "疲惫的云也会变成彩虹",
        "星星总在黑暗最深处",
        "有些话适合慢慢说",
        "你正在做的事让宇宙多了一分温柔"
    };

    @ExceptionHandler(WarmException.class)
    public ResponseEntity<Map<String, String>> handleWarmException(WarmException ex) {
        logger.warn("❗ 业务异常: {}", ex.getMessage());
        Map<String, String> response = new HashMap<>();
        response.put("message", ex.getMessage());
        response.put("warmTip", getWarmTip());
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, String>> handleGeneralException(Exception ex) {
        logger.error("❌ 系统异常", ex);
        Map<String, String> response = new HashMap<>();
        response.put("message", "网络有点小情绪，正在为你准备温暖...");
        response.put("warmTip", "试着摇一摇手机收集星星吧 ✨");
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    private String getWarmTip() {
        return WARM_TIPS[new Random().nextInt(WARM_TIPS.length)];
    }
}
